//
//  EditPersonInfoController.swift
//  maosheng
//
//  Created by lxl on 2019/8/14.
//

import UIKit
import Alamofire
class EditPersonInfoController: RootViewController {
    let personView = EditPersonInfoView()
    var userModel : UserModel?
    override func viewDidLoad() {
        super.viewDidLoad()
        addThePersonView()
        getMyUserInfo()
        // Do any additional setup after loading the view.
        righttBtn = PublicTools.SRightNavBarButtonWith(title: "保存", str_img: nil, action:  #selector(changeUserInfo), controller: self)
        righttBtn?.setTitleColor(.red, for: .normal)
    }
    func addThePersonView() -> Void {
        view.addSubview(personView)
        personView.snp.makeConstraints { (make) in
            make.edges.equalTo(0)
        }
        personView.userBtn.addTarget(self, action: #selector(changeUserAvater), for: .touchUpInside)
    }
    //MARK:-获取用户资料
    func getMyUserInfo() -> Void {
        let url =  "api/services/app/UserProfile/GetMyUserProfileAsync"
        SDataCenter.shared.SGetJsonDataWithUrl(str_url: url, params: nil) { (responseData, isSuccess) in
            
            if isSuccess && responseData is [String : Any]{
                if let model = UserModel.deserialize(from: responseData as? [String : Any]){
                    self.personView.setUserInfo(model: model)
                    self.userModel = model
                }
                
            
            }else{
               
                
            }
        }
    }
    
    
    //MARK:-更改用户信息
   @objc func changeUserInfo() -> Void {
        let editUrl = "api/services/app/UserProfile/CreateOrUpdateMyUserProfileAsync"
        var params = [String : Any]()
        params["nickName"] = personView.nameField.text
        params["headline"] = personView.descField.text
        params["gender"] = personView.sexField.text == "男" ? 1 : 0
        
        SDataCenter.shared.SPostJsonDataWithUrl(str_url: editUrl, params: params) { [weak self] (responseData, isSuccess) in
            if isSuccess{
                self?.backToTop()
            }
        }
    }
    
    //MARK:-更改用户头像
    @objc func changeUserAvater() -> Void {
        let alertController = UIAlertController(title: "", message: "更换头像",
                                                preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let manAction = UIAlertAction(title: "从相册获取", style: .default) { (action) in
            self.presentCameraOrLibrary(btnIndex: 1)
        }
        let womanAction = UIAlertAction(title: "拍摄", style: .default) { (action) in
            self.presentCameraOrLibrary(btnIndex: 0)
        }
        alertController.addAction(womanAction)
        alertController.addAction(manAction)
        alertController.addAction(cancelAction)

        self.present(alertController, animated: true, completion: nil)
    }
    func presentCameraOrLibrary(btnIndex : Int) -> Void {
        if btnIndex == 0 {//相机
            if UIImagePickerController.isSourceTypeAvailable(.camera) == false{
                ProgressHUD.showMsgWithoutView("您的手机不支持拍照")
                return
            }
        }else{
            if #available(iOS 11.0, *) {
                UIScrollView.appearance().contentInsetAdjustmentBehavior = .automatic
            }
        }
        
        let imgPickerVC = UIImagePickerController()
        imgPickerVC.delegate = self
        imgPickerVC.allowsEditing = true
        imgPickerVC.modalTransitionStyle = .coverVertical
        imgPickerVC.sourceType = btnIndex == 0 ? .camera : .photoLibrary
     
        self.present(imgPickerVC, animated: true, completion: nil)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
extension EditPersonInfoController : UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let mediaType = info[UIImagePickerController.InfoKey.mediaType] as? String
        if mediaType != "public.image" {
            return
        }
        
        if #available(iOS 11.0, *) {
            UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
        }
        
        let img = info[.editedImage] as! UIImage
        if picker.sourceType == .camera {
            UIImageWriteToSavedPhotosAlbum(img, self, nil, nil)
        }
        picker.dismiss(animated: true, completion: nil)
        let uploadImg = PublicTools.compressImg(image: img)
        uploadUserImg(uploadImg: uploadImg)
    }
    //MARK:-上传用户头像
    func uploadUserImg(uploadImg : UIImage){

        if let imageData = uploadImg.pngData(){
            var header = [String : String]()
            if UserInfo.getTheUserToken().count > 0{
                header["Authorization"] = "Bearer " + UserInfo.getTheUserToken()
            }
            Alamofire.upload(multipartFormData: { (multipartFormData) in
                //采用post表单上传
                // 参数解释：
                //withName:和后台服务器的name要一致 ；fileName:可以充分利用写成用户的id，但是格式要写对； mimeType：规定的，要上传其他格式可以自行百度查一下
                multipartFormData.append(imageData, withName: "file", fileName: "11111111.jpg", mimeType: "image/jpeg")
                //如果需要上传多个文件,就多添加几个
                //multipartFormData.append(imageData, withName: "file", fileName: "123456.jpg", mimeType: "image/jpeg")
                //......
                if let attachmentId = self.userModel?.avatar?.attachmentId{
                    if attachmentId.count > 0{
                        multipartFormData.append(attachmentId.data(using: .utf8)!, withName: "AttachmentId")
                    }
//                    multipartFormData.append
//                    multipartFormData.appendBodyPart(data: attachmentId.data(using: .utf8), name: "AttachmentId" )

                }
            
                
             
            }, to: URL(string: "http://maosheng.csproj.com/Upload/UploadUserAvatar")! , headers:header) { (encodingResult) in
                switch encodingResult {
                case .success(let upload, _, _):
                    //连接服务器成功后，对json的处理
                    upload.responseJSON { response in
                        //解包
                        guard let result = response.result.value else { return }
                        print("json:\(result)")
                        self.personView.userBtn.setBackgroundImage(uploadImg, for: .normal)
                    }
                    //获取上传进度
                    upload.uploadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in
                        print("图片上传进度: \(progress.fractionCompleted)")
                    }
                case .failure(let encodingError):
                    //打印连接失败原因
                    print(encodingError)
                }
            }
        }
      
    }
}
